Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

258
Visualizações
Getting "MongoExpiredSessionError: Cannot use a session that has ended" when using forEach to update document but why?

I'm just trying to upsert a key value pair i.e. {mark : done} to my Mongo database using id that I have stored in an array.

But for the life of me I can't figure out why if I use a for loop it works fine. But if I use a forEach loop, it gives me a "Cannot use a session that has ended" Error.

I'm hoping someone SO assist in explaining why this happens

Boiler Plate Code

import { MongoClient } from "mongodb";
const uri = "mongodb://localhost:27018/";
const client = new MongoClient(uri);

Function with "for loop" implementation

async function updateMongo1() {
    const db = client.db("testDB");
    const coll = db.collection("testCollection");
    await client.connect();
    try {
        let array = [
            "2021-10-18",
            "2021-10-17",
            "2021-10-16",
            "2021-10-15",
            "2021-10-14",
        ];
        for (let i = 0; i < array.length; i++) {
            await coll.updateOne(
                { _id: array[i] },
                { $set: { mark: "done" } },
                { upsert: true }
            );
        }
    } catch (e) {
        console.error(e.message);
    } finally {
        await client.close();
    }
}

Function with "forEach" implementation

async function updateMongo2() {
    const db = client.db("testDB");
    const coll = db.collection("testCollection");
    await client.connect();
    try {
        let array = [
            "2021-10-18",
            "2021-10-17",
            "2021-10-16",
            "2021-10-15",
            "2021-10-14",
        ];

        array.forEach(async (element) => {
            await coll.updateOne(
                { _id: element },
                { $set: { mark: "done" } },
                { upsert: true }
            );
        });
    } catch (e) {
        console.error(e.message);
    } finally {
        await client.close();
    }
}

running different implementations yields different results.

(async () => {
    //await updateMongo1(); //-> this works
    await updateMongo2(); //-> this gives "MongoExpiredSessionError: Cannot use a session that has ended" what gives??
})();

Please let me know why this happens?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The element variable is an array e.g. ["2021-10-18"]. In the second implementation, you were meant to access element[0] but forgot to so you put an array into the _id field.

I don't know if that's what's specifically causing your error but it is an error in the implementation.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda